
/** 
 * 检测登录状态
 */
import Vue from 'vue';
const storage = require('./storage').default;
const http = require('./http').default;
const M = {
	getToken: function() {
		http.request({
			url: '************', //登录接口eg:/app/refresh/token
			data: {},
			success:function(res){
				let timestamp = parseInt(Date.parse(new Date())/1000);
				let csrfTokenSession = {
					'timeout': parseInt(timestamp)+7000,
					'_token': res._token
				};
				
				//缓存用户登录状态
				 storage.set('csrfTokenSession', csrfTokenSession);
			},
			fail:function(res){
				console.log('请求失败', res);
			}
		});
	},
	checkToken: function() {
		let csrfTokenSession =  storage.get('csrfTokenSession');
		if (
			csrfTokenSession == null 
			|| csrfTokenSession=='' 
			|| typeof csrfTokenSession == 'undefined'
		) {
			this.getToken();
			return false;
		}
		
		let timestamp = parseInt(Date.parse(new Date())/1000);
		
		if (parseInt(csrfTokenSession.timeout) < timestamp) {
			this.getToken();
		}
	},
    hasLogin:function() {
    	let userSession =  storage.get('userSession');
    	if (
    		userSession == null 
    		|| userSession=='' 
    		|| typeof userSession == 'undefined'
    	) {
    		return false;
    	}
    	
		let timestamp = parseInt(Date.parse(new Date())/1000);
		
    	if (parseInt(userSession.timeout) < timestamp) {
    		return false;
    	}
		
		this.checkToken();
    	
    	return true;
    },
    user: function() {
    	let userSession =  storage.get('userSession');
    	if (userSession == null) {
    		return null;
    	}
    	
    	return userSession;
    },
    checkLogin: function() {
		if (this.hasLogin()) {
			//没有登录，跳转到登录页
		   console.log('==没有登录，跳转到登录页==')
		   return false
		} 
			console.log('==已登录，then()==')
			return true
    }
}

export default M;
 